package com.founder.autoCode;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;

import com.founder.autoCode.template.ClassDataParser;
import com.founder.test.Test;

import freemarker.template.Configuration;
import freemarker.template.Template;

public class CreateCodeHelper {

	private Template t;
	
	private String sourceDir;
	
	private List datasource;
	
	private ClassDataParser parser;
	
	public CreateCodeHelper(String templateName, ClassDataParser parser, String sourceDir) {
		this.sourceDir = sourceDir;
		this.parser = parser;
		datasource = new ArrayList();
		
		Configuration cfg = new Configuration();
		//指定模板所在的classpath目录
    	cfg.setClassForTemplateLoading(Test.class, "/");
    	//添加一个"宏"共享变量用来将属性名首字母大写
    	//cfg.setSharedVariable("upperFC", new UpperFirstCharacter());
		try {
			t = cfg.getTemplate(templateName);//指定模板
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	public void readDataSource(File file, String sheetName) {
		try {
			Workbook book = ExcelUtil.createWorkBook(file);
			Sheet sheet =  book.getSheet(sheetName);
			parser.parse(sheet, datasource);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	private void createDir(String dir) {
		File f = new File(dir);
		if (!f.exists()) {
			f.mkdirs();
		}
	}
	
	public void createCode() {
		if (t == null) {
			return;
		}
		try {
			for (Object o : datasource) {
				Map classMap = (Map)o;
				String packageName = (String)classMap.get(ClassDataParser.PACKAGE_NAME);
				String className = (String)classMap.get(ClassDataParser.CLASS_NAME);
				String path = sourceDir + packageName.replace(".", "/");
				createDir(path);
				FileOutputStream fos = new FileOutputStream(new File(path + "/" + className + ".java"));
				try {
					t.process(classMap, new OutputStreamWriter(fos,"utf-8"));
				} finally {
					fos.flush();
					fos.close();
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	

}
